package midd

import (
	"fmt"
	"gin_jwt/config"

	"github.com/dgrijalva/jwt-go"
)

type MyClaims struct {
	Username string `json:"username`
	jwt.StandardClaims
}

//加密
func Token_Encry(user string) string {
	c := MyClaims{

		Username: user,
		StandardClaims: jwt.StandardClaims{
			NotBefore: config.StartTime,
			ExpiresAt: config.EndTime,
			Issuer:    config.IssUer,
		},
	}
	// 使用指定的签名方法创建签名对象
	t := jwt.NewWithClaims(jwt.SigningMethodHS256, c)
	//该方法内部生成签名字符串，再用于获取完整、已签名的token
	s, err := t.SignedString(config.Jwtey)
	if err != nil {
		fmt.Printf("err: %v\n", err)
	}
	return s
}

//解密
func Token_Decrypt(tokenstring string) string {
	s := Token_Encry(config.User_Input)
	mySigningKey := &MyClaims{}
	token, _ := jwt.ParseWithClaims(s, &MyClaims{}, func(t *jwt.Token) (interface{}, error) {
		return mySigningKey, nil
	})
	// fmt.Printf("token: %v\n", token)
	// fmt.Printf("err: %v\n", err)
	fmt.Printf("token.Claims: %v\n", token.Claims.(*MyClaims).Username)
	return token.Claims.(*MyClaims).Username

}
